﻿using AutoClickTool.Common;
using AutoClickTool.Enums;
using AutoClickTool.Models;
using System.Text.Json;

namespace AutoClickTool.Hendlers
{

    public class ActionPool
    {
        public ActionPool()
        {
            var rootPath = Application.StartupPath;
            string filePath = Path.Combine(rootPath, "Data\\Config.json");
            // 判断文件是否存在
            if (File.Exists(filePath))
            {
                // 读取文件内容到变量
                string jsonContent = File.ReadAllText(filePath);
                var data = JsonSerializer.Deserialize<List<ActionConfigModel>>(jsonContent);
                if (data != null && data.Any())
                {
                    try
                    {
                        InitPool(data);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("配置文件无效，请重新上传！");
                    }
                }
                else {
                    MessageBox.Show("配置文件无效，请重新上传！");
                }
            }

        }
        public Dictionary<Keys, ActionModel> Pool = new Dictionary<Keys, ActionModel>();
        private string[] ControllerScope = new string[12] { "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", };
        /// <summary>
        /// 初始化动作池
        /// </summary>
        /// <param name="configs"></param>
        public void InitPool(List<ActionConfigModel> configs)
        {
            Pool.Clear();
            foreach (var config in configs)
            {
                if (string.IsNullOrEmpty(config.Key))
                {
                    throw FriendlyException.Show("未配置【ControllerKey】控制键！");
                }
                if (!ControllerScope.Contains(config.Key))
                {
                    throw FriendlyException.Show("控制键只能为F1-F12的按键！");
                }
                var newAction = new ActionModel();
                newAction.Key=config.Key;
                newAction.Name=config.Name;
                newAction.IsBackTask = config.IsBackTask??false;
                newAction.AppName = config.AppName;
                newAction.AutoUp = config.AutoUp??false;
                if (newAction.IsBackTask)
                {
                    if (string.IsNullOrEmpty(newAction.AppName))
                    {
                        throw FriendlyException.Show("执行后台任务时A程序名【AppName】不能为空！");
                    }
                }
                if (config.UseTimer ?? false)
                {

                    if ((config.UseTimer??false) && !newAction.AutoUp)
                    {
                        throw FriendlyException.Show("定时工作与长按有冲突！");
                    }
                    if (!config.TimerInterval.HasValue)
                    {
                        throw FriendlyException.Show("打开Timer的同时,必须配置间隔时间【TimerInterval】！");
                    }
                    newAction.Timer = new System.Timers.Timer(config.TimerInterval.Value);
                }

                if (config.Click == null || !config.Click.Any())
                {
                    throw FriendlyException.Show("未配置【Click】动作！");
                }
                foreach (var item in config.Click)
                {
                    if (!item.ActionType.HasValue || (item.ActionType != ActionTypeEnum.Key && item.ActionType != ActionTypeEnum.Mouse && item.ActionType != ActionTypeEnum.PlayBack && item.ActionType != ActionTypeEnum.Text))
                    {
                        throw FriendlyException.Show("动作【Click】类型【ActionType】无效！");
                    }
                    var click = new ClickModel(item.ActionType.Value)
                    {
                        PlayBackName = item.PlayBackName,
                        WaitTime = item.WaitTime,
                        LoopNum = item.LoopNum,
                        Sort = item.Sort ?? 0
                    };
                    if (item.ActionType== ActionTypeEnum.Key|| item.ActionType == ActionTypeEnum.Mouse )
                    {
                        if (string.IsNullOrEmpty(item.KeyCode))
                        {
                            throw FriendlyException.Show($"【ActionType】为鼠标/键盘时【KeyCode】不能为空！");
                        }
                        var keyCode = item.KeyCode.ToUpper().ConvertToKeys();
                        if (keyCode == null)
                        {
                            throw FriendlyException.Show($"【KeyCode】无效！");
                        }
                        click.KeyCode = keyCode;
                    }
                    if (item.ActionType == ActionTypeEnum.Text)
                    {
                        if (string.IsNullOrEmpty(item.TextValue))
                        {
                            throw FriendlyException.Show($"【ActionType】为文本时【TextValue】不能为空！");
                        }
                        click.TextValue=item.TextValue;
                    }
                    newAction.AddClickModel(click);
                }
                var controllerKey = config.Key.ToUpper().ConvertToKeys()!.Value;
                if (Pool.ContainsKey(controllerKey))
                {
                    throw FriendlyException.Show($"快捷键【{config.Key}】重复！");
                }
                Pool.Add(controllerKey, newAction);
            }
        }
    }
}
